package reng.tobe.comm.interceptor;

import javax.servlet.ServletContext;

import net.vsame.url2sql.helper.Url2SqlContext;
import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.url.Interceptor;
import net.vsame.url2sql.url.impl.UrlMapping;
import net.vsame.url2sql.url.impl.UrlMapping.Chain;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringInterceptor implements Interceptor {

	private WebApplicationContext springContext;
	private DefaultListableBeanFactory beanFactory;

	@Override
	public void init(UrlMapping urlMapping, ServletContext servletContext) {
		springContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		ConfigurableApplicationContext confiContext = (ConfigurableApplicationContext) springContext;
		beanFactory = (DefaultListableBeanFactory) confiContext.getBeanFactory();
	}

	@Override
	public void invoke(Chain chain) {
		Url2SqlContext c = WebHelper.getContext();
		Object action = c.getAction();
		if(action != null) {
			beanFactory.autowireBean(action);
		}
		chain.next();
	}

	@Override
	public void destroy() {
	}

}
